#ifndef ASYNC_LOG_H_
#define ASYNC_LOG_H_

#include <memory>
#include <vector>

#include "netlib/base/log_buffer.h"
#include "netlib/base/log_file.h"
#include "netlib/base/mutex.h"
#include "netlib/base/noncopyable.h"
#include "netlib/base/thread.h"

namespace netlib {

class LogFile;

class AsyncLog : NonCopyable {
	using Buffer = detail::Buffer<detail::kLargeBuffer>;
	using BufferPtr = std::unique_ptr<Buffer>;
	using BufferVector = std::vector<BufferPtr>;

public:
	explicit AsyncLog(double interval = 3);
	~AsyncLog() = default;

	void InitLogFile(const std::string& basename,
	                 const std::string& dirname,
	                 int check_lines = 2,
	                 time_t interval = 3,
	                 off_t max_bytes = LogFile::kDefaultMaxBytes,
	                 bool is_thread_safe = true);

private:
	void Append(const char* data, size_t len);
	void ThreadFunc();
	void WriteToFile(const BufferVector& /*buffers*/);

	mutable MutexLock mutex_;
	Condition cond_{mutex_};
	BufferPtr cur_buf_;
	BufferPtr next_buf_;
	std::vector<BufferPtr> buffers_;

	double interval_;
	Thread write_thread_;
	std::unique_ptr<LogFile> log_file_;
};

} // namespace netlib

#endif // ASYNC_LOG_H_